<template>
  <div>
    <MyTable :arr="list">
      <template #header
        ><th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th></template
      >
      <template #body="{ row }">
        <td>{{ row.id }}</td>
        <td>{{ row.goods_name }}</td>
        <td>{{ row.goods_price }}</td>
        <td>
          <input
            class="tag-input form-control"
            style="width: 100px"
            type="text"
            v-if="row.inputVisible"
            @blur="row.inputVisible = false"
            @keyup.enter="submitFn(row)"
            @keyup.esc="txt = ''"
            v-model="txt"
            v-focus
          />
          <button
            v-else
            @click.prevent="row.inputVisible = true"
            style="display: block"
            class="btn btn-primary btn-sm add-tag"
          >
            +Tag
          </button>
          <span
            class="badge badge-warning"
            v-for="(item, index) in row.tags"
            :key="index"
            >{{ item }}
          </span>
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="delFn(row.id)">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from '../components/MyTable'
// 目标: 循环商品列表表格
// 1. 封装MyTable.vue 整体表格组件-一套标签和样式
// 2. axios请求数据
// 3. 传入MyTable组件里循环tr显示数据

// 目标: 展示tags标签
// 1. tags数组 - 某个td循环span使用文字
// 2. span设置bs的样式

// 目标: 删除数据
// 1. 删除按钮 - 点击事件
// 2. 作用域插槽把索引值关联出来了
// scope身上就有row和index
// 3. 删除中使用scope.index的索引值
// 4. 删除事件里删除数组里对应索引值的数据
export default {
  methods: {
    submitFn(row) {
      if (this.txt.trim() === '') {
        return alert('请输入内容')
      }
      row.tags.push(this.txt)
      this.txt = ''
    },
    delFn(id) {
      this.list = this.list.filter((item) => item.id !== id)
      // console.log(id)
    },
  },
  directives: {
    focus: {
      inserted(el) {
        el.focus()
      },
    },
  },
  data() {
    return {
      list: [],
      txt: '',
    }
  },
  components: {
    MyTable,
  },
  created() {
    this.$axios({
      url: '/api/goods',
    }).then((res) => {
      // console.log(res)
      this.list = res.data.data
      console.log(this.list)
    })
  },
}
</script>
